# FLANN特征匹配
import cv2
import numpy as np

img1 = cv2.imread('E:\\opencv_photo\\opencv_search.png')
img2 = cv2.imread('E:\\opencv_photo\\opencv_orig.png')
# 灰度化
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 创建surf对象
surf = cv2.xfeatures2d.SURF_create()
# 计算特征点和描述子
kp1, des1 = surf.detectAndCompute(gray1, None)
kp2, des2 = surf.detectAndCompute(gray2, None)

# 创建匹配器
index_params = dict(algorithm = 1, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)

#对描述子进行匹配计算
matchs = flann.knnMatch(des1, des2, k=2)

# 过滤，对所有匹配点进行优化
good = []
for i, (m,n) in enumerate(matchs):
    if m.distance < 0.7 * n.distance:
        good.append(m)

ret = cv2.drawMatchesKnn(img1, kp1, img2, kp2, [good], None)

cv2.imshow('result',ret)
cv2.waitKey()
